﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Atmk.WaterMeter.MIS.Services.Auth
{
    /// <summary>
    /// 基于位运算的权限细粒度控制
    /// </summary>
    public class Purview
    {
        private static int I = 0;


        public static int READ = ++I; //这些权限数值可以取自码表或者其他地方  
        public static int WRITE = ++I;
        public static int MOVE = ++I;
        public static int DELETE = ++I;
        public static int A = ++I;
        public static int B = ++I;

        public static int C = ++I;

        // and more ...  
        public static int MAX = 30; //最大不能超过30  

        /// <summary>
        /// 转换后的权限值，用于存储 
        /// </summary>
        private int _Purview;

        /// <summary>
        /// 构造函数，指定权限列表构造权限对象
        /// </summary>
        public Purview(params int[] values)
        {
            int v = Pur(values[0]);
            for (int i = 1, l = values.Length; i < l; i++)
            {
                v += Pur(values[i]);
            }
            this._Purview = v;
        }

        /// <summary>
        /// 判断当前权限对象是否有指定权限[列表]中所有权限 
        /// </summary>
        /// <param name="values">指定权限[列表]</param>
        /// <returns>boolean true:是，false:否</returns>
        public bool Has(params int[] values)
        {
            int p = Pur(values[0]);
            for (int i = 1, l = values.Length; i < l; i++)
            {
                p += Pur(values[i]);
            }
            return p == (this._Purview & p);
        }

        /// <summary>
        ///计算次方 
        /// </summary>
        /// <param name="p">p 次方</param>
        /// <returns>2^p次方</returns>
        private static int Pur(int p)
        {
            return (int) Math.Pow(2, p);
        }

        /// <summary>
        /// 获取实际的权限数值
        /// </summary>
        /// <returns>实际的权限数值</returns>
        public int GetPurviewValue()
        {
            return this._Purview;
        }
    }
}